﻿// Fill out your copyright notice in the Description page of Project Settings.


#include "DesignPatterns/StatePattern.h"
#include "Kismet/GameplayStatics.h"

void UStateBaseStateWidget::EnterState()
{
	OnEnterState();
}

void UStateBaseStateWidget::ExitState()
{
	OnExitState();
}

void UStateBaseStateWidget::OnEnterState_Implementation()
{
	AddToViewport();
}

void UStateBaseStateWidget::OnExitState_Implementation()
{
	RemoveFromParent();
}

void AStateUIStateManager::EnterState(TSubclassOf<UStateBaseStateWidget> StateWidgetClass)
{
	if (CurrentStateWidget != nullptr)
	{
		CurrentStateWidget->ExitState();
	}

	if (WidgetInstances.Contains(StateWidgetClass))
	{
		CurrentStateWidget = WidgetInstances.FindRef(StateWidgetClass);
	} else
	{
		APlayerController* PC = UGameplayStatics::GetPlayerController(GetWorld(), 0);
		CurrentStateWidget = CreateWidget<UStateBaseStateWidget>(PC, StateWidgetClass);
		WidgetInstances.Add(StateWidgetClass, CurrentStateWidget);
	}
	CurrentStateWidget->EnterState();
}

void AStateUIStateManager::ExitAllState()
{
	for (auto& Elem : WidgetInstances)
	{
		(Elem.Value)->ExitState();
	}
}
